import { ref, reactive, computed } from 'vue'
import { defineStore } from 'pinia'
import request, { query, report } from '../utils/request'

export const useUserStore = defineStore('user', () => {
  //使用reactive不能使用ref.value方式赋值
  const account = reactive({
    id: '',
    name: 'world', //localStorage.getItem('user')
    role: ''
  })
  const userinfo = ref({})
  const user = computed(() => {
    const { name } = account
    return name
  })
  //使用Promise包裹axios对象，更换resolve的参数
  const login = (params) => {
    return new Promise((resolve) => {
      report('/api/Test/login', params).then(
        (res) => {
          if (res.status == 201) {
            account.id = res.data.id
            account.name = res.data.name
            account.role = res.data.role
            //localStorage.setItem('token', res.data.token)
            resolve(true)
          } else resolve(false)
        },
        (reason) => {
          console.log(reason)
        }
      )
    })
  }
  //使用callback，替代resolve及参数
  const editInfo = (callback) => {
    let promise = report('/api/Test/user', userinfo.value)
    promise.then((res) => {
      console.log(res.data.info)
      callback(res.status == 201)
    })
    return promise
  }
  //用异步函数的方式承接Promise对象，返回Promise对象
  const getInfo = async () => {
    const res = await query('/api/Test/user')
    userinfo.value = res.data
    return res
  }

  return { account, user, login, userinfo, getInfo, editInfo }
})
